/*
 * @Description:
 * @Author: william
 * @Date: 2025-02-05 09:08:10
 * @LastEditors: william
 * @LastEditTime: 2025-08-12 15:25:36
 */
import { apiLoginUserInfo } from '@/api/user'
import { getUmsToken, setUmsToken, removeUmsToken } from '@/utils/cookies'
import router, { resetRouter } from '@/router'
import { getPerm } from '@/utils/index'
// import { Encrypt } from '@/utils/secret'
import EventSourceClient from '@/utils/SSE.js'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref(getUmsToken())
    const uid = ref('')
    const userInfo = ref({})
    const perms = ref([])
    const menus = ref([])
    const eventSource = ref(null)

    const startSSEClient = () => {
      const token = getUmsToken()
      if (token) {
        eventSource.value = new EventSourceClient(
          `${import.meta.env.VITE_APP_SSE_API}/sse/connect?token=${token}`
        )
      }
    }

    startSSEClient()

    const getBtnPerm = url => {
      return getPerm(perms.value, url)
    }
    const login = loginInfo => {
      return g_api.user
        .apiLogin({
          ...loginInfo
          // username: loginInfo.username.trim(),
          // password: Encrypt(loginInfo.password)
        })
        .then(({ data }) => {
          const expires = new Date(data.expiresAt)
          setUmsToken(data.accessToken, expires)
          token.value = data.accessToken
          localStorage.setItem('tokenKey', new Date().getTime())
          startSSEClient()
        })
    }

    const getUserInfo = _ => {
      return apiLoginUserInfo().then(({ code, data }) => {
        if (code === '200' && data) {
          userInfo.value = data
          const permissionStore = usePermissionStore()
          // 管理员展示组织管理页面
          if (data.superAdmin) {
            permissionStore.routes.forEach(item => {
              if (item.name === 'userCenter') {
                item.redirect = '/userCenter/organize'
                item.children.unshift({
                  path: '/userCenter/organize',
                  name: 'organize',
                  component: () =>
                    import('@/views/userCenter/organize/index.vue'),
                  meta: {
                    title: 'organizeManage'
                  }
                })
              }
              g_router.addRoute(item)
            })
          }
        }
        return data
      })
    }

    const logoutUser = () => {
      removeUmsToken()
      token.value = ''
      userInfo.value = {}
      localStorage.setItem('tokenKey', new Date().getTime())
      // menus.value = []
      usePermissionStore().resetRoutes()
      resetRouter()
      eventSource.value && eventSource.value.close() // 关闭推送连接
      if (
        ['login', '404', '403'].indexOf(router.currentRoute.value.path) > -1 ||
        router.currentRoute.value.path === '/userCenter/organize'
      ) {
        router.replace(`/login`)
      } else {
        router.replace(`/login?redirect=${router.currentRoute.value.fullPath}`)
      }
    }

    const resetToken = _ => {
      token.value = ''
      removeUmsToken()
    }

    const setUid = id => {
      uid.value = id
    }

    return {
      token,
      userInfo,
      perms,
      menus,
      eventSource,
      startSSEClient,
      getBtnPerm,
      login,
      getUserInfo,
      logoutUser,
      resetToken,
      setUid
    }
  }
  // {
  //   persist: true // 配置持久化
  // }
)
export function useOutsideUserStore() {
  return useUserStore(g_store)
}
